
use redis::Commands;
use shq_common::prelude::{NumberCard, ThreeNumber, get_ch_pool, get_redis_cli};
pub struct HomeNumberCards {
    lr_zb: NumberCard,
    ck_zb: NumberCard,
    dk_zb: NumberCard,
    ybspm_zb: NumberCard,
}
impl HomeNumberCards {
    pub fn get_lr_zb(&self) -> &NumberCard {
        &self.lr_zb
    }
    pub fn get_ck_zb(&self) -> &NumberCard {
        &self.ck_zb
    }
     pub fn get_dk_zb(&self) -> &NumberCard {
        &self.dk_zb
    }
    pub fn get_ybspm_zb(&self) -> &NumberCard {
        &self.ybspm_zb
    }
}
impl HomeNumberCards {
    pub async fn load_from_cache() -> anyhow::Result<Self> {
        let mut rcli=get_redis_cli().get_connection()?;
        let iexist:bool=rcli.exists("home_lr_zb:0")?;
        if !iexist {
            cache_lr_zb().await?;
        }
        let iexist:bool=rcli.exists("home_gm_zb:0")?;
        if !iexist {
            cache_gm_zb().await?;
        }
        let iexist:bool=rcli.exists("home_ybspm_zb:0")?;
        if !iexist {
            cache_ybspm_zb().await?;
        }
        let mut ny=0u32;
        let mut ck_nums: Vec<ThreeNumber> = Vec::with_capacity(3);
        let mut dk_nums: Vec<ThreeNumber> = Vec::with_capacity(3);
        for i in 1..=3 {
            let hkey=format!("home_gm_zb:{}", i);
            ny=rcli.hget(&hkey,"ny")?;
            let val=rcli.hget(&hkey,"dq")?;
            let bsn=rcli.hget(&hkey,"bsn")?;
            let bsy=rcli.hget(&hkey,"bsy")?;
            ck_nums.push(ThreeNumber {
                val,
                bsn,
                bsy,
            });
        }
        for i in 4..=6 {
            let hkey=format!("home_gm_zb:{}", i);
            ny=rcli.hget(&hkey,"ny")?;
            let val=rcli.hget(&hkey,"dq")?;
            let bsn=rcli.hget(&hkey,"bsn")?;
            let bsy=rcli.hget(&hkey,"bsy")?;
            dk_nums.push(ThreeNumber {
                val,
                bsn,
                bsy,
            });
        }
        let ck_zb=NumberCard{
            ny,
            nums: ck_nums,
        };
        let dk_zb=NumberCard{
            ny,
            nums: dk_nums,
        };
        let mut lr_nums: Vec<ThreeNumber> = Vec::with_capacity(3);
        for i in 1..=3 {
            let hkey=format!("home_lr_zb:{}", i);
            let mut rcli=get_redis_cli().get_connection()?;
            ny=rcli.hget(&hkey,"ny")?;
            let val=rcli.hget(&hkey,"dq")?;
            let bsn=rcli.hget(&hkey,"bsn")?;
            let bsy=rcli.hget(&hkey,"bsy")?;
            lr_nums.push(ThreeNumber {
                val,
                bsn,
                bsy,
            });
        }
        let lr_zb=NumberCard{
            ny,
            nums: lr_nums,
        };
        let mut ybspm_zb_nums: Vec<ThreeNumber> = Vec::with_capacity(3);
        for i in 1..=3 {
            let hkey=format!("home_ybspm_zb:{}", i);
            let mut rcli=get_redis_cli().get_connection()?;
            ny=rcli.hget(&hkey,"ny")?;
            let val=rcli.hget(&hkey,"dq")?;
            let bsn=rcli.hget(&hkey,"bsn")?;
            let bsy=rcli.hget(&hkey,"bsy")?;
            ybspm_zb_nums.push(ThreeNumber {
                val,
                bsn,
                bsy,
            });
        }
        let ybspm_zb=NumberCard{
            ny,
            nums: ybspm_zb_nums,
        };
        Ok(HomeNumberCards {
            ck_zb,
            dk_zb,
            lr_zb,
            ybspm_zb,
        })
    }
    pub fn clear_cache(&self) -> anyhow::Result<()> {
        let mut rcli=get_redis_cli().get_connection()?;
        for i in 1..=3 {
            let hkey=format!("home_gm_zb:{}", i);
            let _: () = rcli.del(&hkey)?;
        }
        for i in 1..=6 {
            let hkey=format!("home_lr_zb:{}", i);
            let _: () = rcli.del(&hkey)?;
        }
        for i in 1..=3 {
            let hkey=format!("home_ybspm_zb:{}", i);
            let _: () = rcli.del(&hkey)?;
        }
        Ok(())
    }
}
async fn cache_gm_zb() -> anyhow::Result<()> {
    let mut client = get_ch_pool().get_handle().await?;
    let sql_str = r#"with (select max(ny) from data_gfn_jydtpm) as ny_dq,
     toUInt32(ny_dq/100) as nf,toUInt32(ny_dq%nf) as yf,
     if(yf=1,(nf-1)*100+12,nf*100+(yf-1)) as ny_sy,
     (nf-1)*100+12 as ny_sn
SELECT ny,c_jydt_1_1/10000 ckgm,c_jydt_1_2/10000 ckgm_gs,c_jydt_1_3/10000 ckgm_ls,c_jydt_12_1/10000 dkgm,c_jydt_12_2/10000 dkgm_gs,c_jydt_12_5/10000 dkgm_ls
FROM data_gfn_jydtpm final WHERE ny in (ny_dq,ny_sy,ny_sn) and dwmc='上海分行' order by ny desc"#;
    let block = client.query(sql_str).fetch_all().await?;
    let mut ny = 0u32;
    let mut nums: Vec<ThreeNumber> = Vec::with_capacity(6);
    for (i, row) in block.rows().enumerate() {
        if i == 0 {
            ny = row.get("ny")?;
            for j in 1..=6 {
                let val: f64 = row.get(j)?;
                nums.push(ThreeNumber {
                    val,
                    bsn: 0.0,
                    bsy: 0.0,
                });
            }
        } else if i == 1 {
            for j in 1..=6 {
                let bsn: f64 = row.get(j)?;
                nums[j-1].bsn = if bsn==0.0 { 0.0 } else { nums[j-1].val-bsn };
            }
        } else if i == 2 {
            for j in 1..=6 {
                let bsy: f64 = row.get(j)?;
                nums[j-1].bsy = if bsy==0.0 { 0.0 } else { nums[j-1].val-bsy };
            }
        }
    }
    for (i, num) in nums.iter().enumerate() {
        let hkey=format!("home_gm_zb:{}", i+1);
        let mut rcli=get_redis_cli().get_connection()?;
        let vals=vec![("ny", ny.to_string()),("dq",num.val.to_string()),("bsn",num.bsn.to_string()),("bsy",num.bsy.to_string())];
        let _:()=rcli.hset_multiple(hkey, &vals)?;
    }
    Ok(())
}

async fn cache_lr_zb() -> anyhow::Result<()> {
    let mut client = get_ch_pool().get_handle().await?;
    let sql_str = r#"with (select max(ny) from data_gfn_jydtpm) as ny_dq,
     toUInt32(ny_dq/100) as nf,toUInt32(ny_dq%nf) as yf,
     if(yf=1,(nf-1)*100+12,nf*100+(yf-1)) as ny_sy,
     (nf-1)*100+12 as ny_sn
SELECT ny,c_lrzb_1_13/10000 khlr,c_lrzb_1_1/10000 khlr_gs,c_lrzb_1_2/10000 khlr_ls
FROM data_gfn_jydtpm final WHERE ny in (ny_dq,ny_sy,ny_sn) and dwmc='上海分行' order by ny desc"#;
    let block = client.query(sql_str).fetch_all().await?;
    let mut ny = 0u32;
    let mut nums: Vec<ThreeNumber> = Vec::with_capacity(3);
    for (i, row) in block.rows().enumerate() {
        if i == 0 {
            ny = row.get("ny")?;
            for j in 1..=3 {
                let val: f64 = row.get(j)?;
                nums.push(ThreeNumber {
                    val,
                    bsn: 0.0,
                    bsy: 0.0,
                });
            }
        } else if i == 1 {
            for j in 1..=3 {
                let bsn: f64 = row.get(j)?;
                nums[j-1].bsn = if bsn==0.0 { 0.0 } else { nums[j-1].val-bsn };
            }
        } else if i == 2 {
            for j in 1..=3 {
                let bsy: f64 = row.get(j)?;
                nums[j-1].bsy = if bsy==0.0 { 0.0 } else { nums[j-1].val-bsy };
            }
        }
    }
    for (i, num) in nums.iter().enumerate() {
        let hkey=format!("home_lr_zb:{}", i+1);
        let mut rcli=get_redis_cli().get_connection()?;
        let vals=vec![("ny", ny.to_string()),("dq",num.val.to_string()),("bsn",num.bsn.to_string()),("bsy",num.bsy.to_string())];
        let _:()=rcli.hset_multiple(hkey, &vals)?;
    }
    Ok(())
}

async fn cache_ybspm_zb() -> anyhow::Result<()> {
    let mut client = get_ch_pool().get_handle().await?;
    let sql_str = r#"with (select max(ny) from data_ybs_jyyjpm) as ny_dq,toUInt32(ny_dq/100) as nf,toUInt32(ny_dq%nf) as yf,
     if(yf=1,(nf-1)*100+12,nf*100+(yf-1)) as ny_sy,
     (nf-1)*100+12 as ny_sn
SELECT ny,pm,zbwc50_pm,ysgx50_pm
FROM data_ybs_jyyjpm final
WHERE dwmc='上海分行' and ny in (ny_dq,ny_sy,ny_sn)"#;
    let block = client.query(sql_str).fetch_all().await?;
    let mut ny = 0u32;
    let mut nums: Vec<ThreeNumber> = Vec::with_capacity(3);
    for (i, row) in block.rows().enumerate() {
        if i == 0 {
            ny = row.get("ny")?;
            for j in 1..=3 {
                let val: i32 = row.get(j)?;
                nums.push(ThreeNumber {
                    val: val as f64,
                    bsn: 0.0,
                    bsy: 0.0,
                });
            }
        } else if i == 1 {
            for j in 1..=3 {
                let bsn: i32 = row.get(j)?;
                nums[j-1].bsn = if bsn==0 { 0.0 } else { bsn as f64-nums[j-1].val };
            }
        } else if i == 2 {
            for j in 1..=3 {
                let bsy: i32 = row.get(j)?;
                nums[j-1].bsy = if bsy==0 { 0.0 } else { bsy as f64-nums[j-1].val };
            }
        }
    }
    for (i, num) in nums.iter().enumerate() {
        let hkey=format!("home_ybspm_zb:{}", i+1);
        let mut rcli=get_redis_cli().get_connection()?;
        let vals=vec![("ny", ny.to_string()),("dq",num.val.to_string()),("bsn",num.bsn.to_string()),("bsy",num.bsy.to_string())];
        let _:()=rcli.hset_multiple(hkey, &vals)?;
    }
    Ok(())
}
